package com.baijiayun.liveuibase.devicetesting

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothHeadset
import android.bluetooth.BluetoothProfile
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.startActivity
import androidx.lifecycle.Observer
import com.baijiayun.liveuibase.R
import com.baijiayun.liveuibase.base.BaseScreenActivity
import com.baijiayun.liveuibase.base.getViewModel
import com.baijiayun.liveuibase.devicetesting.fragment.DeviceTestingDialogFragment
import com.baijiayun.liveuibase.devicetesting.fragment.DeviceTestingFragment
import com.baijiayun.liveuibase.devicetesting.fragment.DeviceTestingPrepareFragment
import com.baijiayun.liveuibase.devicetesting.fragment.DeviceTestingResultFragment
import kotlinx.android.synthetic.main.bjy_base_activity_device_testing.*

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class DeviceTestingActivity : BaseScreenActivity() {

    private val prepareFragment by lazy {
        DeviceTestingPrepareFragment()
    }

    private val giveUpDialog by lazy {
        DeviceTestingDialogFragment()
    }

    private val testingFragment by lazy {
        DeviceTestingFragment()
    }

    private val testingResultFragment by lazy {
        DeviceTestingResultFragment()
    }

    private val netWorkStateReceiver = NetWorkStateReceiver()
    private val earphoneStateReceiver = EarphoneStateReceiver()

    private lateinit var deviceTestingViewModel: DeviceTestingViewModel

    override fun getLayoutId() = R.layout.bjy_base_activity_device_testing

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window: Window = window
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = resources.getColor(R.color.base_white)
        }

        deviceTestingViewModel = getViewModel { DeviceTestingViewModel() }
        deviceTestingViewModel.setContext(this)

        val netFilter = IntentFilter()
        netFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(netWorkStateReceiver, netFilter)

        val earphoneFilter = IntentFilter()
        earphoneFilter.addAction(Intent.ACTION_HEADSET_PLUG)
        earphoneFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
        registerReceiver(earphoneStateReceiver, earphoneFilter)

        deviceTestingViewModel.getEarphoneStatus(this)
        initAction()
        bjy_base_device_testing_give_up_tv.setOnClickListener {
            showGiveUpDialog()
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            addFragment(R.id.bjy_base_device_testing_fragment_container, prepareFragment, DeviceTestingPrepareFragment::class.simpleName)
        } else {
            requestPermissions(arrayOf(Manifest.permission.READ_PHONE_STATE), 0)
        }
    }

    private fun initAction() {
        deviceTestingViewModel.getTestStepChange()
                .observe(this, Observer {
                    if (it == DeviceTestingViewModel.TestStep.TestEnd) {
                        bjy_base_device_testing_give_up_tv.visibility = View.INVISIBLE
                    } else {
                        bjy_base_device_testing_give_up_tv.visibility = View.VISIBLE
                    }
                    when (it) {
                        DeviceTestingViewModel.TestStep.Start -> replaceFragment(R.id.bjy_base_device_testing_fragment_container, testingFragment)
                        DeviceTestingViewModel.TestStep.TestEnd -> replaceFragment(R.id.bjy_base_device_testing_fragment_container, testingResultFragment)
                        else -> return@Observer
                    }
                })
    }

    override fun onBackPressed() {
        showGiveUpDialog()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(netWorkStateReceiver)
        unregisterReceiver(earphoneStateReceiver)
    }

    private fun showGiveUpDialog() {
        giveUpDialog.setTitle(getString(R.string.bjy_base_device_testing_quit_give_up))
        giveUpDialog.setContent(getString(R.string.bjy_base_device_testing_quit_tip))
        giveUpDialog.setNegativeButtonText(getString(R.string.bjy_base_device_testing_give_up))
        giveUpDialog.setPositiveButtonText(getString(R.string.bjy_base_device_testing_continue))
        giveUpDialog.setButtonClickedListener(object : DeviceTestingDialogFragment.OnButtonClickedListener {
            override fun onPositive() {
                giveUpDialog.dismissAllowingStateLoss()
            }

            override fun onNegative() {
                finish()
            }
        })
        giveUpDialog.show(supportFragmentManager, DeviceTestingDialogFragment::class.simpleName)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            addFragment(R.id.bjy_base_device_testing_fragment_container, prepareFragment, DeviceTestingPrepareFragment::class.simpleName)
        } else if (requestCode == 0) {
            finish()
        }
    }

    inner class NetWorkStateReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val connMgr = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
            val wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            val dataNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
            if (wifiNetworkInfo == null || dataNetworkInfo == null) {
                deviceTestingViewModel.netState.value = DeviceTestingViewModel.NetState.None
                return
            }
            if (!wifiNetworkInfo.isConnected && !dataNetworkInfo.isConnected) {
                deviceTestingViewModel.netState.value = DeviceTestingViewModel.NetState.None
            } else if (wifiNetworkInfo.isConnected) {
                deviceTestingViewModel.netState.value = DeviceTestingViewModel.NetState.Wifi
            } else if (dataNetworkInfo.isConnected) {
                deviceTestingViewModel.netState.value = DeviceTestingViewModel.NetState.Mobile
            }
        }
    }

    companion object {
        fun launch(context: Context) {
            startActivity(context, Intent(context, DeviceTestingActivity::class.java), null)
        }
    }

    inner class EarphoneStateReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED == action) {
                val adapter = BluetoothAdapter.getDefaultAdapter()
                val state = adapter.getProfileConnectionState(BluetoothProfile.HEADSET)
                if (BluetoothProfile.STATE_CONNECTED == state) {
                    deviceTestingViewModel.earphoneState.value = true
                }
                if (BluetoothProfile.STATE_DISCONNECTED == state) {
                    deviceTestingViewModel.earphoneState.value = false
                }
            } else if (Intent.ACTION_HEADSET_PLUG == action) {
                if (intent.hasExtra("state")) {
                    if (intent.getIntExtra("state", 0) == 0) {
                        deviceTestingViewModel.earphoneState.value = false
                    } else if (intent.getIntExtra("state", 0) == 1) {
                        deviceTestingViewModel.earphoneState.value = true
                    }
                }
            }
        }
    }
}